package com.base.sweb;

import android.Manifest;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.base.commonlib.base.CBaseBarActivity;
import com.base.commonlib.utils.MultiFileUtil;
import com.base.commonlib.utils.PermissionCheckUtil;
import com.base.commonlib.utils.ToastUtil;
import com.base.sweb.bean.TaskInfo;
import com.base.sweb.databinding.ActivityFileDisplayBinding;
import com.base.sweb.file.FileReaderView;
import com.base.sweb.utils.DownloadRunnable;
import com.base.sweb.utils.StatusBarUtil;
import com.base.sweb.utils.ToolsUtils;

import java.io.File;


/**
 * describe：文件阅读类
 *
 * @author ：鲁宇峰 on 2018/8/7 11：14
 *         email：luyufengc@enn.cn
 */
@Route(path = Constance.ACTIVITY_URL_FILEDISPLAY_ACTIVITY)
public class FileDisplayActivity extends CBaseBarActivity implements PermissionCheckUtil.OnPermissionRequestSuccess {

    private FileReaderView mDocumentReaderView;

    private DownloadRunnable runnable;//下载任务
    private TaskInfo info = null;//任务信息
    @Autowired
    boolean isPdf;


    private ActivityFileDisplayBinding mBinding;
    @Autowired
    String name;
    @Autowired
    String title;
    @Autowired
    String url;
    //用于更新进度的Handler
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //使用Handler制造一个200毫秒为周期的循环
            handler.sendEmptyMessageDelayed(1, 200);
            //计算下载进度
            int l = (int) ((float) info.getCompletedLen() / (float) info.getContentLen() * 100);
            //设置进度条进度
            mBinding.webProgress.setProgress(l);
            if (l>=100) {//当进度>=100时，取消Handler循环
                handler.removeCallbacksAndMessages(null);
                mBinding.webProgress.hide();
                if (getFragmentManager().isDestroyed()){

                }else {
                    mDocumentReaderView.show(ToolsUtils.getApkDir() + name);
                }
            }
            return true;
        }
    });

    public void init() {
        mBinding = (ActivityFileDisplayBinding) mRootBinding;
        super.init();
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtil.setRootViewFitsSystemWindows(this,true);
        //设置状态栏透明
//        StatusBarUtil.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtil.setStatusBarColor(this,0x55000000);
        }
        mDocumentReaderView = findViewById(R.id.documentReaderView);
        String[] ps=new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE
        };
        PermissionCheckUtil.checkAndRequest(this, ps,this);
    }

    @Override
    protected void start() {
        setBackNavigation();
        setBarTitle(title);
        setRigImg(R.mipmap.ic_print, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (url!=null) {
                    MultiFileUtil.showPdf(mContext, ToolsUtils.getApkDir()+name);
                }else {
                    ToastUtil.show("未检测到文件");
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDocumentReaderView != null) {
            mDocumentReaderView.stop();
        }
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_file_display;
    }

    @Override
    public void onPermissionSuccess() {
        startLoad();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        startLoad();
    }
    private void startLoad(){
        if (url.startsWith("http")) {
            File file = new File(ToolsUtils.getApkDir() + name);
            if (file.exists()) {
                if (getFragmentManager().isDestroyed())return;
                mDocumentReaderView.show(file.getPath());
                return;
            }
            file.mkdirs();
            mBinding.webProgress.show();
            info = new TaskInfo();
            info.setName(name);
            info.setPath(ToolsUtils.getApkDir());
            info.setUrl(url);
            //下载
            runnable = new DownloadRunnable(info);
            //开始下载任务
            new Thread(runnable).start();
            //开始Handler循环
            handler.sendEmptyMessageDelayed(1, 200);

        } else {
            if (getFragmentManager().isDestroyed())return;
            mDocumentReaderView.show(url);
        }
    }
}
